﻿using Glorysoft.EAP.Core.Enums;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FluentScheduler;
using Glorysoft.EAP.Core;
using Glorysoft.Auto.Xfw;
using Serilog.Core;
using Glorysoft.EAP.RC.EAPClient;
using System.IO;
using System.Linq;
using System.Drawing;

namespace Glorysoft.EAP.EAPwell
{
    /// <summary>
    /// 监控monitor文件计划调度器固定计划调度器
    /// </summary>
    public class FixedTimer : IJob
    {
        private DbService dbServer = null;
        private readonly Logger CimLogger;
        public FixedTimer()
        {
            CimLogger = XfwContext.LogManager.DbLogger;
        }
        public void Execute()
        {
            dbServer = new DbService();       
            //查有没有week的记录，没有创建一条
            DateTime nowTime = DateTime.Now;
            // 获取本周第一天 ,星期一为第一天  
            int weeknow = Convert.ToInt32(nowTime.DayOfWeek);
            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;
            DateTime FirstDay = nowTime.AddDays(daydiff).Date;//本周第一天                                                             
            int lastWeekDay = Convert.ToInt32(nowTime.DayOfWeek); // 获取本周最后一天,//星期天为最后一天  
            lastWeekDay = lastWeekDay == 0 ? (7 - lastWeekDay) : lastWeekDay;
            int lastWeekDiff = (7 - lastWeekDay);
            DateTime LastDay = nowTime.AddDays(lastWeekDiff + 1).Date.AddSeconds(-1);//本周最后一天
            var weekid = FirstDay.ToString("yyyyMMdd");

          

            var rptWeekid = dbServer.SeleteWeekid(weekid);
            if (rptWeekid == null)//没有建本周的weekid,新增一条
            {
                dbServer.InsertMsgTo_Monitor_Time(0, DateTime.Now, weekid, DateTime.Now,"N");
            }
            EAPClientService clientService = new EAPClientService();
            string path = Dict.Current.MonitorTestDataPath;
            bool Exists = Directory.Exists(path);
            if (Exists == true)
            {
                DirectoryInfo root = new DirectoryInfo(path);
                DirectoryInfo directory = root.GetDirectories().OrderBy(n => n.LastWriteTime).Last();
                DirectoryInfo directoryInfo = new DirectoryInfo(directory.FullName);
                FileInfo[] files = directoryInfo.GetFiles();
                List<string> file = new List<string>();
                List<string> filelist = new List<string>();
                List<DateTime> timelist = new List<DateTime>();
                foreach (FileInfo f in files)
                {
                    string name = f.Name;
                   // if (name.Contains(Dict.Current.TesterID))//Dict.Current.TesterID
                   // {
                        string fullName = f.FullName;
                        DateTime filedt = f.LastWriteTime;//获取文件最后的写入时间
                        filelist.Add(name + ";" + filedt);
                   // }
                }
                if (filelist.Count() == 0)//文件里是空，本周内设备未进行monitor测试
                {
                    return;
                }
                else
                {
                    for (int i = 0; i < filelist.Count; i++)//文件夹里有文件
                    {
                        var temptime = DateTime.Parse(filelist[i].Split(";")[1]);
                        var tempfile = filelist[i].Split(";")[0];
                        timelist.Add(temptime);
                        file.Add(tempfile);
                    }
                    timelist.Sort((x, y) => DateTime.Compare(x.Date, y.Date));
                    DateTime times = DateTime.Parse(timelist.Last().ToString());
                    var filename = file.Last().ToString();
                    int weekno = Convert.ToInt32(nowTime.DayOfWeek);
                    //本周2
                    DateTime date2 = FirstDay.AddDays(1).AddHours(23).AddMinutes(59).AddSeconds(59);    
                    //本周4
                    DateTime date4 = FirstDay.AddDays(3).AddHours(23).AddMinutes(59).AddSeconds(59);
                    //本周6
                    DateTime date6 = FirstDay.AddDays(5).AddHours(23).AddMinutes(59).AddSeconds(59);
                    var dbWeekid = dbServer.SeleteWeekid(weekid);
                    int count = Convert.ToInt32(dbWeekid.COUNT);
                    if (weekno < 3)
                    {                                   
                        if (times > FirstDay && times < date2)
                        {
                            //已有测试文件，不进行锁机                       
                            dbServer.UpdateMsgTo_Monitor_Time(count, DateTime.Now, weekid, DateTime.Now, "Y");
                            CimLogger.Information($"循环检查：本周已进行monitor测试，文件名称:{filename}");
                            //dbServer.InsertMsgInfo($"循环检查：本周已进行monitor测试，文件名称:{filename}");
                        }
                    }
                    else if (weekno > 2 && weekno < 5)
                    {
                     
                        if (times > date2 && times < date4)
                        {
                            //已有测试文件，不进行锁机                                                
                            dbServer.UpdateMsgTo_Monitor_Time(2, DateTime.Now, weekid, DateTime.Now, "Y");
                            CimLogger.Information($"循环检查：本周已进行monitor测试，文件名称:{filename}");
                            //dbServer.InsertMsgInfo($"循环检查：本周已进行monitor测试，文件名称:{filename}");
                        }
                    }
                    else if (weekno > 4 && weekno < 7)
                    {                                                                                                         
                        if (times > date4 && times < date6)
                        {
                            //已有测试文件，不进行锁机                                               
                            dbServer.UpdateMsgTo_Monitor_Time(3, DateTime.Now, weekid, DateTime.Now, "Y");
                            CimLogger.Information($"循环检查：本周已进行monitor测试，文件名称:{filename}");
                            //dbServer.InsertMsgInfo($"循环检查：本周已进行monitor测试，文件名称:{filename}");
                        }
                    }                   
                    else
                    {
                        return;
                    }
                }
            } 
        }
    } 
}
